 var handler;
// 用于保存实体的对象
var gon;
// 设置当前的编辑点
let currentPoint;
// 判断是否处于编辑状态
let isEditting = false;
// 清空编辑点ID数组
let pointsId = [];
// 历史轨迹集合  //长度为4  记录前三次数据  最后一次为当前的数据
let gonList = []
//记录最后一个经纬度信息
let lastPosition = []
 
const editActive = (viewer) => {
    handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
    //取消之前的监听函数
    handler.setInputAction(event => {
        if (isEditting && currentPoint) {
            
            // 获取屏幕坐标，移动监听与点击有所不同，所以有起始位置和终点位置
            let windowPosition = event.endPosition;
            // 将屏幕坐标转为笛卡尔坐标
            let ellipsoid = viewer.scene.globe.ellipsoid;
            let cartesian = viewer.camera.pickEllipsoid(windowPosition, ellipsoid);
            // 如果点击到地球外，那么返回
            if (!cartesian) {
                return;
            }
            // 更新编辑点的位置
            currentPoint.position = cartesian;
            // 创建面标每个点位置信息的数组，并循环赋值
            let points = [];
            for (let id of pointsId) {
                points.push(viewer.entities.getById(id).position._value);
            }
            if (gon.type == "polygon") {
              // 更新面标的位置数组
                gon.polygon.hierarchy = new Cesium.CallbackProperty(function () {
                    return new Cesium.PolygonHierarchy(points);
                }, false);
                gon.polyline.positions = new Cesium.CallbackProperty(function () {
                    return points.concat([points[0]]);
                }, false);
            } else if (gon.type == "polyline") {
                gon.polyline.positions = new Cesium.CallbackProperty(function () {
                    return points;
                }, false);
            }
            lastPosition = points
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);


    handler.setInputAction(event => {
        var pick = viewer.scene.pick(event.position);
        let pointList = [];
        
        if (pick && pick.id !== gon && pick.id.name !== "editPointEntity") {
            isEditting = false;
            currentPoint = undefined;
            // 移除编辑点，清空编辑点数组
            for (let id of pointsId) {
                viewer.entities.removeById(id);
            }
            pointsId = [];
            editDeactive(viewer);
        }
 
        if (pick && pick.id && pick.id.name == "drawEntity" && !isEditting) {
            gon = pick.id;
            //判断要素为点线面类型
            let pointList = []
            if (gon.type == "polygon") {
                pointList = gon.polygon.hierarchy._value ? gon.polygon.hierarchy._value.positions : gon.polygon.hierarchy._callback().positions
            } else if (gon.type == "polyline") {
                pointList = gon.polyline.positions._value ? gon.polyline.positions._value : gon.polyline.positions._callback()
            }            
            //抽8个点出来
            let length18 = Math.floor(pointList.length / 18)  
    
            pointList.forEach((item,index) => {
              if(index === 0. || index % length18 === 0){
                let point  = viewer.entities.add({
                    id:`point${index+1}`,
                    name: "editPointEntity",
                    position: item,
                    type: item.type ? item.type : "",
                    point: {
                      // color: Cesium.Color.SKYBLUE.withAlpha(index === 0. || index % length18 === 0 ? 1 : 0.2),
                      // outlineColor: Cesium.Color.YELLOW.withAlpha(index === 0 || index % length18 === 0 ? 1 : 0),
                      color: Cesium.Color.SKYBLUE,
                      outlineColor: Cesium.Color.YELLOW,
                      pixelSize: 10,
                      outlineWidth: 3,
                      disableDepthTestDistance: Number.POSITIVE_INFINITY,
                      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                    },
                });
                // 保存点的ID以便删除
                pointsId.push(point.id);
               }
              });

              gonList[0] = pointList
            // 设置编辑状态为true
            isEditting = true;
            // 禁止地球旋转和缩放，地球的旋转会对鼠标移动监听有影响，所以需要禁止
            viewer.scene.screenSpaceCameraController.enableRotate = false;
            viewer.scene.screenSpaceCameraController.enableZoom = false;
        } else if (pick && pick.id && pick.id.name === "editPointEntity") {
            currentPoint = pick.id;
            viewer.scene.screenSpaceCameraController.enableRotate = false;
            viewer.scene.screenSpaceCameraController.enableZoom = false;
        }

    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
 
    handler.setInputAction(() => {
        // 移除当前编辑点
        currentPoint = undefined;
        viewer.scene.screenSpaceCameraController.enableRotate = true;
        viewer.scene.screenSpaceCameraController.enableZoom = true;

        if(gon && lastPosition.length>0){
          if(gonList.length > 3){
            gonList.splice(0,1)
          }
          gonList.push(lastPosition)
        }
    }, Cesium.ScreenSpaceEventType.LEFT_UP);

    handler.setInputAction((event) => {
      let pick = viewer.scene.pick(event.position);
      if(pick&&pick.id.id.indexOf('point')>-1){
        pick.id.point.color = Cesium.Color.SKYBLUE
        pick.id.point.outlineColor = Cesium.Color.YELLOW
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
 
    // 点击右键事件
    handler.setInputAction(() => {
        editDeactive(viewer);
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};
 

const revoke = () => {
  if(gonList.length>1){
      let points = gonList[gonList.length - 2]
      gon.polyline.positions = new Cesium.CallbackProperty(function () {
        return points;
    }, false);
    gonList.splice(gonList.length-1,1)
  }
}

const editDeactive = (viewer) => {
    if (isEditting) {
        // // 移除监听器
        // if (handler !== null && !handler.isDestroyed()) {
        //     handler.destroy();
        // }
        // 移除编辑点，清空编辑点数组
        for (let id of pointsId) {
            viewer.entities.removeById(id);
        }
        pointsId = [];
        gonList = []
        lastPosition = []
        isEditting = false;
    }
};

const getData = () =>{
  let arr = gonList[gonList.length - 1]
  return arr
}

const destroyEdit = (viewer) => {
  if (isEditting) {
      // 移除监听器
      if (handler !== null && !handler.isDestroyed()) {
          handler.destroy();
      }
      // 移除编辑点，清空编辑点数组
      for (let id of pointsId) {
          viewer.entities.removeById(id);
      }
      pointsId = [];
      isEditting = false;
  }
};
 
export {
    editActive,
    editDeactive,
    destroyEdit,
    getData,
    revoke
};
